package structures.table.symboltable;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 *
 * @author Volodymyr Pogorelov
 */
public class GlobalItemInfoTable {

    private HashSet<String> keyWords;
    //TODO: Explain this to avoid confusing of other the developers
    private HashMap<ItemInfo, ItemInfo> items = new HashMap<ItemInfo, ItemInfo>();

    public GlobalItemInfoTable(List<String> keyWords) {
        this.keyWords = new HashSet<String>(keyWords.size());
        ItemInfo info;
        for (String kw : keyWords) {
            this.keyWords.add(kw);
            info = new TerminalItemInfo(kw, TerminalType.KEY_WORD);
            items.put(info, info);
        }
    }

    public TerminalItemInfo addToken(String name, TerminalType type) {
        return (TerminalItemInfo) addItem(new TerminalItemInfo(name,
                keyWords.contains(name) ? TerminalType.KEY_WORD : type));
    }
    
    public ItemInfo addGrammarItem(String name, boolean isNonterminal){
        if(isNonterminal){
            return new NonTerminalInfo(name);
        }
        if(keyWords.contains(name)){
            return new TerminalItemInfo(name, TerminalType.KEY_WORD);
        }
        if(name.equals("IDENTIFIER")){
            return new TerminalItemInfo(name, TerminalType.IDENTIFIER);
        }
        if(name.equals("CHARACTER_LITERAL")){
            return new TerminalItemInfo(name, TerminalType.CHARACTER_LITERAL);
        }
        if(name.equals("INT_LITERAL")){
            return new TerminalItemInfo(name, TerminalType.INT_LITERAL);
        }
        if(name.equals("REAL_LITERAL")){
            return new TerminalItemInfo(name, TerminalType.REAL_LITERAL);
        }
        if(name.equals("STRING_LITERAL")){
            return new TerminalItemInfo(name, TerminalType.STRING_LITERAL);
        }
        return new TerminalItemInfo(name, TerminalType.PUNCTUATOR);
        
    }

    public ItemInfo addItem(ItemInfo info) {
        ItemInfo oldInfo = items.get(info);
        if (oldInfo == null) {
            items.put(info, info);
            return info;
        }
        return oldInfo;
    }

    public boolean isKeyWord(String name) {
        return keyWords.contains(name);
    }
}
